package webservices;

import interfaces.IRegister;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import webservices.helper.Helper;

public class RegisterImpl implements IRegister {
	
	public String register(String username, String password, String email, String identityNo) {
		String returnMessage = "";
		Connection con = null;
		try {
			con = Helper.getDBConnection();

			ResultSet rs1 = con.createStatement().executeQuery("select count(1) from user where Name=\'" + username + "\' or Email=\'" + email+"\'");
			rs1.next();
			int dupCount = rs1.getInt(1);
			if (dupCount > 0){
				return  "<response name='fail' value='用户名或邮箱已被注册' />";
			}
			
			String identity = identityNo.startsWith("ST") ? "STUDENT" : "TEACHER";
			
			PreparedStatement insertSt = con.prepareStatement("insert into user(Name,Password,Email,Identity) values(?,?,?,?)");
			insertSt.setString(1, username);
			insertSt.setString(2, password);
			insertSt.setString(3, email);
			insertSt.setString(4, identity);
			insertSt.executeUpdate();
				
			ResultSet rs2 = con.createStatement().executeQuery("select max(UserID) from user");
			rs2.next();
			String userid = rs2.getString(1);
			returnMessage += "<response name='success' />";
			returnMessage += "<response name='UserID' value='"+userid+"' />";

			
		} catch (SQLException e) {
			returnMessage = "<response name='fail' value='>";
			e.printStackTrace();
		} finally {
			try {
				con.close();
			} catch (SQLException e) {}
		}
		return returnMessage;
	}
}